package com.shqcjd.yunweiyanoperator.ui.activity.preview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class WordActivity extends BaseActivity {

    @BindView(R.id.pdfView)
    PDFView pdfView;
    @BindView(R.id.ib_back)
    ImageButton ib_back;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.tv_toolbar_right)
    TextView tvToolbarRight;


    private String url;//文件url
    private String name;//文件名称
    private Context context;

    private BaseDownloadTask singleTask;
    private String mFilePath;
    public int singleTaskId = 0;
    private boolean isDownload = false;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_word;
    }

    @Override
    public void init() {
        super.init();
        url = getIntent().getStringExtra("url");
        name = getIntent().getStringExtra("name");
        context = this;
    }

    @Override
    public void initView() {
        super.initView();
        tvToolbarRight.setVisibility(View.VISIBLE);
        tvToolbarCenter.setText(name);
        ib_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        wordToPdf(url);

    }

    private void wordToPdf(String url){
        Logger.i("url====:"+url);
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        ApiService.word2pf(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("加载中...");
                    }

                    @Override
                    public void _onNext(ResponseData<String> responseData) {
                        if(responseData.retCode==10000){
                            startDown(responseData.data, name);
                        }else{
                            ToastUtils.showShort(context, responseData.retMsg);
                        }
                        hideWaitingDialog();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void loadPDF(String url) {
        File f = new File(url);
        pdfView.fromFile(f)
                .defaultPage(0) //设置默认显示第几页
                .onPageChange(new OnPageChangeListener() {
                    @Override
                    public void onPageChanged(int page, int pageCount) {
                        tvToolbarRight.setText(String.format("%s /%s 页", page + 1, pageCount));

                    }
                })
                .enableAnnotationRendering(true)
                .swipeHorizontal(false)
                .spacing(10)
                .onLoad(new OnLoadCompleteListener() {
                    @Override
                    public void loadComplete(int nbPages) {
                    }
                })
                .onPageError(new OnPageErrorListener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onPageError(int page, Throwable t) {
                    }
                })
                .load();
    }


    /**
     * 下载文件
     */
    public void startDown(String fileUrl, String fileName) {
        if (isDownload)
            return;
        File file = null;
        try {
            file = new File(FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "qc_save");
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
        isDownload = true;

        mFilePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "qc_save" + File.separator + fileName;
        singleTask = FileDownloader.getImpl().create(fileUrl)
//                .setPath(mSinglePath,false)
                .setPath(mFilePath)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                //.setWifiRequired(isWifiRequired:boolean)//设置任务是否只允许在Wifi网络环境下进行下载。 默认值 false
                //.pause(void)//暂停下载任务(也可以理解为停止下载，但是在start的时候默认会断点续传)
                //.setAutoRetryTimes(autoRetryTimes:int)//当请求或下载或写文件过程中存在错误时，自动重试次数，默认为0次
                //.setSyncCallback(syncCallback:boolean)//如果设为true, 所有FileDownloadListener中的回调都会直接在下载线程中回调而不抛到ui线程, 默认为false
//                .setForceReDownload(true)//是否强制重新下载
                //.isReusedOldFile(void):boolean//判断是否是直接使用了旧文件(检测是有效文件)，没有启动下载
                //.setTag()
                .setForceReDownload(false)
                .setListener(new FileDownloadSampleListener() {
                    //等待，已经进入下载队列
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei", "pending taskId:" + task.getId() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes);

                    }

                    //下载进度回调
                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei", "progress taskId:" + task.getId() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes + ",speed:" + task.getSpeed());
                    }

                    //在完成前同步调用该方法，此时已经下载完成
                    @Override
                    protected void blockComplete(final BaseDownloadTask task) {
                        Log.d("feifei", "blockComplete taskId:" + task.getId() + ",filePath:" + task.getPath() + ",fileName:" + task.getFilename() + ",speed:" + task.getSpeed() + ",isReuse:" + task.reuse());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                isDownload = false;
//                                openFile(VideoChatViewActivity.this, task.getPath());
                                loadPDF(task.getPath());
                            }
                        });

                        Logger.e("线程Thread.currentThread().getName() :" + Thread.currentThread().getName());
                    }

                    //完成整个下载过程
                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.d("feifei", "completed taskId:" + task.getId() + ",isReuse:" + task.reuse());
                        isDownload = false;
                    }

                    //暂停下载
                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.d("feifei", "paused taskId:" + task.getId() + ",soFarBytes:" + soFarBytes + ",totalBytes:" + totalBytes + ",percent:" + soFarBytes * 1.0 / totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("feifei", "error taskId:" + task.getId() + ",e:" + e.getLocalizedMessage());
//                        loadingError();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                isDownload = false;
                                ToastUtils.showShort(context, "该文件不支持打开");
                            }
                        });
                    }

                    //在下载队列中(正在等待/正在下载)已经存在相同下载连接与相同存储路径的任务
                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Log.d("feifei", "warn taskId:" + task.getId());
                    }
                });
        singleTaskId = singleTask.start();
    }
}
